package com.shujia.flink.table

import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment
import org.apache.flink.types.Row

object Demo1Blink {
  def main(args: Array[String]): Unit = {

    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() //使用blink计划器
      .inStreamingMode() //流处理模型
      .build()

    //创建table环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)



    //创建表
    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE student (
        | id String,
        | name String,
        | age int,
        | gender STRING,
        | clazz STRING
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'student',
        | 'properties.bootstrap.servers' = 'node1:9092,node2:9092,master:9092',
        | 'properties.group.id' = 'asdsadsada',
        | 'format' = 'json',
        | 'scan.startup.mode' = 'latest-offset'
        |)
        |
      """.stripMargin)


    val student: Table = bsTableEnv.from("student")

    //打印表结构
    student.printSchema()

    //转换成流打印结果
    val ds: DataStream[Row] = bsTableEnv.toAppendStream[Row](student)

    //    ds.print()


    val clazzNumTable: Table = bsTableEnv.sqlQuery(
      """
        |select clazz,count(1) from student group by clazz
        |
      """.stripMargin)

    //转换成流打印结果
    bsTableEnv.toRetractStream[Row](clazzNumTable).print()


    //启动flink程序
    bsEnv.execute("table")

  }
}
